package com.question.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.question.business.auth.model.dto.UserDetailDTO;
import com.question.common.utils.CurrentUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自动填充字段
 *
 * @author star
 * @since 2021/6/12
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Autowired
    protected CurrentUserUtil currentUserUtil;

    /**
     * 插入自动填充
     *
     * @param metaObject 元数据
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        UserDetailDTO user = currentUserUtil.getUser();
        this.fillStrategy(metaObject, "createdUser", user.getId());
    }

    /**
     * 更新自动填充
     *
     * @param metaObject 元数据
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        UserDetailDTO user = currentUserUtil.getUser();
        this.fillStrategy(metaObject, "updatedUser", user.getId());
        this.fillStrategy(metaObject, "updatedTime", LocalDateTime.now());
    }
}
